/**
 * KAYO APPLIANCE CHAINS.
 * Copyright (c) 2016-2016 All Rights Reserved.
 */
package com.leku.mse.mq.listener.member;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.leku.commons.datasource.DataSourceContextHolder;
import com.leku.commons.umpush.AndroidPushClient;
import com.leku.commons.umpush.IosPushClient;
import com.leku.commons.umpush.PushContentEntity;
import com.leku.commons.util.StringUtil;
import com.leku.mse.constants.DataSourceConstant;
import com.leku.mse.dao.member.MessageDao;
import com.leku.mse.entity.MemberEntity;
import com.leku.mse.entity.MessSwitchEntity;
import com.leku.mse.entity.MessageEntity;
import com.leku.mse.service.cache.MemberCache;

/**
 * 功能描述: 消息数据同步监听
 *
 * @author suiying
 * @created 2017年5月31日
 * @version 1.0.0
 */
public class MessageSyncListener implements MessageListener {

    private static final Logger LOG = LoggerFactory.getLogger(MessageSyncListener.class);

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MemberCache memberCacheService;

    @Autowired
    private AndroidPushClient adPushClient;

    @Autowired
    private IosPushClient iosPushClient;

    /*
     * (non-Javadoc)
     * @see javax.jms.MessageListener#onMessage(javax.jms.Message)
     */
    @Override
    public void onMessage(Message message) {

        MessageEntity messageEntity = null;
        String msg = null;
        try {
            TextMessage textMsg = (TextMessage) message;
            msg = textMsg.getText();
            LOG.info("个人消息:" + msg);
            messageEntity = JSON.parseObject(msg, MessageEntity.class);
        } catch (Exception e) {
            LOG.error("同步个人消息异常", msg);
        }

        if (messageEntity == null || StringUtil.isEmpty(messageEntity.getMemberCode())
                || messageEntity.getMemberCode().equals(messageEntity.getFromMember())) {
            return;
        }

        // 设置为会员中心数据库
        DataSourceContextHolder.setDataSourceType(DataSourceConstant.memDataSource());

        // 数据入库
        try {
            messageDao.insertMessage(messageEntity);

            // 增加消息数
            memberCacheService.incrMemberMussNum(messageEntity.getMemberCode(), messageEntity.getAppCode(), 1);
        } catch (Exception e) {
            LOG.error("同步个人消息数据入库异常", msg);
        }

        // 推送友盟消息
        try {
            MemberEntity member = memberCacheService.getMember(messageEntity.getFromMember());
            String userName = "";
            if (member != null) {
                userName = member.getNick();
            }

            if ("praise".equals(messageEntity.getMessageType()) || "lovediary".equals(messageEntity.getMessageType())
                    || "reply".equals(messageEntity.getMessageType())) {

                if (isMessSwitch(messageEntity.getMemberCode(), messageEntity.getMessageType())) {
                    adPushClient.pushCustomcast(
                            preAdPushContent(messageEntity.getMessageType(), messageEntity.getMemberCode(),
                                    preMsg(userName, messageEntity.getMessageType(), messageEntity.getRelaType())));

                    iosPushClient.pushCustomcast(
                            preIosPushContent(messageEntity.getMessageType(), messageEntity.getMemberCode(),
                                    preMsg(userName, messageEntity.getMessageType(), messageEntity.getRelaType())));
                }
            }
        } catch (Exception e) {
            LOG.error("友盟推送异常", e);
        }
    }

    /**
     * 
     * 功能描述: 安卓的推送消息
     *
     * @param type
     * @param memberCode
     * @param memberName
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private PushContentEntity preAdPushContent(String type, String memberCode, String msg) {

        PushContentEntity push = new PushContentEntity();

        push.setUserId(memberCode);
        push.setPushType("7");
        push.setPushId("");
        push.setTitle("时光手帐");

        push.setText(msg);

        return push;
    }

    /**
     * 
     * 功能描述: 安卓的推送消息
     *
     * @param type
     * @param memberCode
     * @param memberName
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private PushContentEntity preIosPushContent(String type, String memberCode, String msg) {

        PushContentEntity push = new PushContentEntity();

        push.setUserId(memberCode);
        push.setPushType("message");
        push.setPushId("");
        push.setTitle("时光手帐");

        push.setText(msg);

        return push;
    }

    /**
     * 
     * 功能描述: 查询消息开关
     *
     * @param memberCode
     * @param messType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private boolean isMessSwitch(String memberCode, String messType) {
        // 检查会员开关
        MessSwitchEntity messSwitch = messageDao.getMessSwitch(memberCode);

        if (messSwitch == null) {
            return false;
        }

        boolean flag = false;

        if ("praise".equals(messType)) {
            if (messSwitch.getPraise() != null && messSwitch.getPraise() == 1) {
                flag = true;
            }
        } else if ("lovediary".equals(messType)) {
            if (messSwitch.getDiary() != null && messSwitch.getDiary() == 1) {
                flag = true;
            }
        } else if ("reply".equals(messType)) {
            if (messSwitch.getReply() != null && messSwitch.getReply() == 1) {
                flag = true;
            }
        }

        return flag;
    }

    /**
     * 
     * 功能描述:组装内容
     *
     * @param msgType
     * @param relaType
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private String preMsg(String memberName, String msgType, String relaType) {
        String mess = memberName + " ";
        if ("lovediary".equals(msgType)) {
            mess += "点赞了你的作品";
        } else if ("praise".equals(msgType)) {
            mess += "点赞了你的动态";
        } else if ("reply".equals(msgType)) {
            if ("diary".equals(relaType)) {
                mess += "评论了你的作品";
            } else {
                mess += "评论了你的动态";
            }
        }

        return mess;
    }
}
